<cfparam name="attributes.query" type="query">
<cfparam name="attributes.indexdirectory" type="string">
<cfparam name="attributes.storecolumns" type="string" default="#attributes.query.columnlist#">
<cfparam name="attributes.indexcolumns" type="string" default="#attributes.query.columnlist#">

<!--- 
This default root is used in cases where indexdirectory is a simple value, not
a full path.
--->
<cfset defaultroot = "#server.coldfusion.rootdir#/luceneindex">

<!--- ToDo: This is a dupe of code from indexfiles. We need to move to a code base where this stuff is centralized. --->
<cfif not find("\", attributes.indexdirectory) and not find("/", attributes.indexdirectory)>
	<cfset attributes.indexdirectory = defaultroot & "/" & attributes.indexdirectory>
</cfif>

<!--- create indexdirectory if it doesn't exist --->
<cfif not directoryExists(attributes.indexdirectory)>
	<cfdirectory action="create" directory="#attributes.indexdirectory#">
</cfif>

<!--- If we don't have anything, just leave. --->
<cfif attributes.query.recordCount is 0>
	<cfexit method="exitTag">
</cfif>

<!--- Make my stuff --->
<cfset indexWriter = createObject("java", "org.apache.lucene.index.IndexWriter")>
<cfset analyzer = createObject("java", "org.apache.lucene.analysis.standard.StandardAnalyzer").init()>

<!--- third arg nukes old data --->
<cfset indexWriter.init(attributes.indexdirectory, analyzer, true)>

<cfset fs = createObject("java", "org.apache.lucene.document.Field$Store")>
<cfset fi = createObject("java", "org.apache.lucene.document.Field$Index")>

<cfloop query="attributes.query">
	<!--- 
	for each column:
		a column can be stored yes or no
		a column can be searchable yes or no
	--->
	
    <cfset doc = createObject("java", "org.apache.lucene.document.Document")>

	<cfloop index="col" list="#attributes.query.columnlist#">
	    <cfset field = createObject("java", "org.apache.lucene.document.Field")>
		<!--- are we storing? --->
		<cfif listFindNoCase(attributes.storecolumns, col)>
			<cfset stored = fs.YES>
		<cfelse>
			<cfset stored = fs.NO>
		</cfif>

		<!--- are we indexing --->
		<cfif listFindNoCase(attributes.indexcolumns, col)>
			<cfset indexed = fi.TOKENIZED>
		<cfelse>
			<cfset indexed = fi.NO>
		</cfif>

		<!-- are we skipping this? --->
		<cfif listFindNoCase(attributes.storecolumns, col) or listFindNoCase(attributes.indexcolumns, col)>
			<!--- get the value --->
			<cfset value = attributes.query[col][currentRow]>
			
		    <cfset field = createObject("java", "org.apache.lucene.document.Field")>
		    <cfset field.init(lcase(col), javaCast("string",value), stored, indexed)>
		    <cfset doc.add(field)>
		</cfif>			
	</cfloop>
	
	<cfset indexWriter.addDocument(doc)>
</cfloop> 
			 
<cfset indexWriter.close()>			